package com.leigang.simple.service.impl;

import com.leigang.simple.service.IGenService;
import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class GenServiceImpl implements IGenService {
    @Value("${file.path}")
    public String filePath;
    @Value("${page.timeout}")
    public Integer timeout;
    @Value("${page.width}")
    public Integer pageWidth;
    @Value("${page.after.thread.sleep}")
    public Integer pageAfterThreadSleep;

    @Override
    public void genImage(String url) throws Exception{
        int height = getHeight(url);
        ArrayList<String> arrayList = new ArrayList<>();
        Viewport viewport = new Viewport();
        viewport.setWidth(pageWidth);
        viewport.setHeight(height);
        LaunchOptions options = new LaunchOptionsBuilder()
                .withArgs(arrayList)
                .withHeadless(true)
                .withViewport(viewport)
                .build();
        arrayList.add("--no-sandbox");
        arrayList.add("--disable-setuid-sandbox");
        Browser browser = Puppeteer.launch(options);
        Page page = browser.newPage();
        PageNavigateOptions pageNavigateOptions = new PageNavigateOptions();
        pageNavigateOptions.setTimeout(timeout);
//        page.setDefaultTimeout(3600000);
        page.goTo(url, pageNavigateOptions);
        Thread.sleep(pageAfterThreadSleep);
        ScreenshotOptions screenshotOptions = new ScreenshotOptions();
        Clip clip = new Clip();
        clip.setHeight(height);
        clip.setWidth(pageWidth);
        clip.setX(0);
        clip.setY(0);
        //设置截图范围
        screenshotOptions.setClip(clip);
        //设置存放的路径
        screenshotOptions.setPath(filePath);
        screenshotOptions.setType("png");
        page.screenshot(screenshotOptions);
        page.close();
        browser.close();
    }


    private int getHeight(String url) throws Exception{
        ArrayList<String> arrayList = new ArrayList<>();
        LaunchOptions options = new LaunchOptionsBuilder()
                .withArgs(arrayList)
                .withHeadless(true)
                .build();
        arrayList.add("--no-sandbox");
        arrayList.add("--disable-setuid-sandbox");
        Browser browser = Puppeteer.launch(options);
        Page page = browser.newPage();
        PageNavigateOptions pageNavigateOptions = new PageNavigateOptions();
        pageNavigateOptions.setTimeout(timeout);
//        page.setDefaultTimeout(3600000);
        page.goTo(url, pageNavigateOptions);
        int height = (Integer) page.evaluate("document.body.scrollHeight");
        Thread.sleep(pageAfterThreadSleep);
        page.close();
        browser.close();
        return height;
    }
}
